﻿//开始调用Ajax
/*
url:要访问的链接   参数类型:String
paramMap:参数列表  参数类型:Map
callBack:回调接口  参数类型:js对象
注:callBack对象类一定要有onSuccess(ResultBean rb)方法和onFail(ResultBean rb)方法
*/

//Ajax post
function AjaxStart(url, paramet, callBack) {
    ajax_start(url, paramet, callBack, "json");
}

//Jsonp格式 
function AjaxJsonp(url, param, callBack) {
    ajax_start(url, param, callBack, "jsonp");
}

function ajax_start(url, data, callBack, dataType) {
    if (map.get(url) != null)
        return;
    map.put(url, "true");
    var type = data != "" ? "POST" : "GET";
    wait.show("加载");
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: data,
        jsonpCallback: "JsonpCallback", //自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名，也可以写"?"，jQuery会自动为你处理数据
        success: function (json) {
            wait.dismiss();
            map.remove(url);
            checkAjax(json);    //状态检测
            callBack(json);     //json方式回调
        },
        error: function (rs) {
            map.remove(url);
            toast.show("请求异常!");
        }
    });
}

function checkAjax(json) {
    if (json == null) {
        toast.show("服务器返回数据失败");
        return;
    }
    if (json.Code == 7) {
        //限制单点登录,异地cookies 删掉
        delCookie("token");
        delCookie("userid");
        delCookie("logintype");
        delCookie("parentid");
    }
}

//jsonp请求时,回调的空方法
function JsonpCallback(data, callback) {
}

var map = new Map();

function Map() {
    this.arr = new Array();
    var struct = function (key, value) {
        this.key = key;
        this.value = value;
    };
    
    // 添加map键值对 
    this.put = function (key, value) {
        for (var i = 0; i < this.arr.length; i++) {
            if (this.arr[i].key === key) {
                this.arr[i].value = value;
                return;
            }
        };
        this.arr[this.arr.length] = new struct(key, value);
    };
    // 根据key获取value 
    this.get = function (key) {
        for (var i = 0; i < this.arr.length; i++) {
            if (this.arr[i].key === key) {
                return this.arr[i].value;
            }
        }
        return null;
    };
    // 根据key删除 
    this.remove = function (key) {
        var v;
        for (var i = 0; i < this.arr.length; i++) {
            v = this.arr.pop();
            if (v.key === key) {
                continue;
            }
            this.arr.unshift(v);
        }
    }
    // 获取map键值对个数 
    this.size = function () {
        return this.arr.length;
    }
    // 判断map是否为空 
    this.isEmpty = function () {
        return this.arr.length <= 0;
    }
}